package logic

import (
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"house_srv/house"
	"house_srv/internal/svc"
	"house_srv/models/mysql"
	"house_srv/models/redisinit"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *house.UserLoginRequest) (*house.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	user := mysql.User{}

	err := user.UserInfo(in.Mobile)
	if err != nil {
		logx.Error("用户信息错误", err)
		return nil, errors.New("用户信息错误")
	}
	if user.ID == 0 {
		user.Mobile = in.Mobile
		user.Password = in.Password
		err = user.Create()
		if err != nil {
			logx.Error("创建注册信息失败", err)
			return nil, errors.New("创建注册信息失败")
		}
	}
	get := redisinit.Rdb.Get(l.ctx, "SendSmslogin"+in.Mobile)
	if get.Val() != in.SendSms {
		er := redisinit.Rdb.Get(l.ctx, "SendSms"+"er"+in.Mobile)
		if er.Val() >= "5" {
			redisinit.Rdb.Del(l.ctx, "SendSms"+"er"+in.Mobile)
			logx.Error("超过5次则需要重新发送")
			return nil, fmt.Errorf("超过5次则需要重新发送")
		}
	} else {
		redisinit.Rdb.Incr(l.ctx, "SendSms"+"er"+in.Mobile)
		logx.Error("获取短信验证码错误")
		return nil, errors.New("获取短信验证码错误")
	}

	return &house.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
